package ldh.im.rpc.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RpcException extends RuntimeException {

    private static final Logger LOGGER = LoggerFactory.getLogger(RpcException.class);
    private ErrorCode errorCode;
    private String localSeq;

    public RpcException(ErrorCode errorCode, Object...params) {
        super(buildMessage(null, errorCode, params));
        this.errorCode = errorCode;
    }

    public RpcException(ErrorCode errorCode, Throwable cause, Object...params) {
        super(buildMessage(cause, errorCode, params), cause);
        this.errorCode = errorCode;
        if (cause != null && cause instanceof ErrorCode) {
            this.errorCode = (ErrorCode) cause;
        }
    }

    public ErrorCode getErrorCode() {
        return errorCode;
    }

    public String getLocalSeq() {
        return localSeq;
    }

    public void setLocalSeq(String localSeq) {
        this.localSeq = localSeq;
    }

    private static String buildMessage(Throwable throwable, ErrorCode errorCode, Object...params) {
        if (throwable != null && throwable instanceof ErrorCode) {
            return throwable.getMessage();
        }
        if (errorCode.getErrorMessage().contains("%")) {
            try {
                return String.format(errorCode.getErrorMessage(), params);
            } catch (Exception e) {
                return throwable.getMessage();
            }

        }
        return errorCode.getErrorMessage();
    }
}
